package com.ekin.attendance.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ekin.attendance.converter.LeaveConverter;
import com.ekin.attendance.mapper.LeaveMapper;
import com.ekin.attendance.model.entity.Leave;
import com.ekin.attendance.model.form.LeaveForm;
import com.ekin.attendance.model.query.LeavePageQuery;
import com.ekin.attendance.model.vo.LeavePageVO;
import com.ekin.attendance.service.LeaveService;
import com.ekin.common.exception.BusinessException;
import com.ekin.system.model.dto.CurrentUserDTO;
import com.ekin.system.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class LeaveServiceImpl extends ServiceImpl<LeaveMapper, Leave> implements LeaveService {
    private final LeaveConverter leaveConverter;
    private final UserService userService;
    /**
     * 请假分页列表
     * @param queryParams 分页查询对象
     */
    @Override
    public Page<LeavePageVO> getLeavePage(LeavePageQuery queryParams) {
        //查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();

        //查询数据
        return this.baseMapper.getLeavePage(new Page<>(pageNum, pageSize), queryParams);

    }
    /**
     * 新增请假
     * @param formData 请假对象
     */
    @Override
    public boolean saveLeave(LeaveForm formData) {
        //转换为实体
        Leave entity = leaveConverter.toEntity(formData);
        //调用方法UserService 获得当前登录用户信息
        CurrentUserDTO currentUserInfo = userService.getCurrentUserInfo();
       //申请人姓名
       entity.setApplyer(currentUserInfo.getNickname());
       //暂时没用
       entity.setApplyerNumber(currentUserInfo.getUserNumber());
       //申请人工号
       entity.setApplyerId(currentUserInfo.getUsername());
       //申请人部门
        entity.setDeptId(currentUserInfo.getDeptId());
        // 生成申请单号
        String applyNo = generateApplyNo();
        entity.setApplyerNumber(applyNo);
        return this.save(entity);
    }
    /**
     * 请假表单数据
     * @param id 请假ID
     */
    @Override
    public LeaveForm getLeaveForm(Long id) {
        // 获取请假单
        Leave entity = this.getById(id);
        if (entity == null) {
            throw new BusinessException("请假单不存在");
        }
        return leaveConverter.toForm(entity);
    }
    /**
     * 修改请假
     * @param id 请假ID
     * @param leaveForm 请假对象
     */
    @Override
    public boolean updateLeave(Long id, LeaveForm leaveForm) {
        // 获取请假单
        Leave entity = this.getById(id);
        if (entity == null) {
            throw new BusinessException("请假单不存在");
        }
        // 更新字典
        Leave leave = leaveConverter.toEntity(leaveForm);
        leave.setId(id);
        return this.updateById(leave);
    }

    @Override
    public void deleteLeaves(String idsStr)
    {
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "删除的请假数据为空");
        // 逻辑删除
        List<Long> ids = Arrays.stream(idsStr.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        this.removeByIds(ids);
    }
    /**
     * 生成申请单号
     */
    private String generateApplyNo() {
        LocalDate today = LocalDate.now();
        String datePrefix = today.format(DateTimeFormatter.ofPattern("yyyyMMdd")); // 20250619
        String fullPrefix = "QJSQ" + datePrefix;

        // 查询数据库中最大的单号（当天）
        String maxNo = baseMapper.getMaxApplyNoByPrefix(fullPrefix);

        int nextNumber = 1;

        if (maxNo != null && maxNo.startsWith(fullPrefix)) {
            try {
                String numberPart = maxNo.substring(fullPrefix.length());
                nextNumber = Integer.parseInt(numberPart) + 1;
            } catch (NumberFormatException ignored) {
                // 解析失败，保持 nextNumber = 1
            }
        }

        // 格式化为4位数字，前面补零
        return String.format("%s%04d", fullPrefix, nextNumber);
    }

}
